<template>
  <BasicModal
    v-bind="$attrs"
    @register="editRegister"
    title="编辑终端类型"
    :width="436"
    :minHeight="140"
    centered
    @ok="confirmSubmit"
    @cancel="resetModal"
  >
    <div class="modify-box">
      <BasicForm @register="editForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup name="terminalEdit">
import { ref, reactive, createVNode } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, FormSchema, useForm } from '@/components/Form/index'
import { userStore } from '@/store/modules/user'
import { Modal, message, Button } from 'ant-design-vue'
import { cloneDeep } from 'lodash-es'
import api from '@/api'
import { ExclamationCircleFilled } from '@ant-design/icons-vue'

const { switchRpa } = api
const userModule = userStore()

const confirmLoading = ref(false)

const emit = defineEmits(['operateSuccess', 'register'])

const modalInfo = reactive<any>({
  tenantId: '',
  rpaType: 0
})

const schemas: FormSchema[] = [
  {
    field: 'rpaType',
    component: 'Select',
    label: '开票终端类型',
    componentProps: {
      allowClear: false,
      options: [
        {
          label: '本地基础',
          value: 3,
          key: 3
        },
        {
          label: '云端基础',
          value: 1,
          key: 1
        }
      ]
    }
  }
]

const [editForm, { setFieldsValue, getFieldsValue, validate, resetFields }] = useForm({
  showActionButtonGroup: false,
  labelWidth: 80,
  schemas,
  baseColProps: {
    span: 24
  }
})

const [editRegister, { changeOkLoading, closeModal }] = useModalInner((data) => {
  let messageData = cloneDeep(data)
  modalInfo.tenantId = messageData.tenantId
  modalInfo.rpaType = Number(messageData.rpaType)
  setFieldsValue({
    rpaType: modalInfo.rpaType
  })
})

const resetModal = () => {
  resetFields()
  changeOkLoading(false)
}

const confirmSubmit = () => {
  let formValue = getFieldsValue()
  if (formValue.rpaType == modalInfo.rpaType) {
    message.warn('未修改当前终端类型')
  } else {
    Modal.confirm({
      title: '温馨提醒',
      centered: true,
      icon: createVNode(ExclamationCircleFilled),
      content: '修改开票终端类型后，企业需要重新在数票通登录数电账号才能生效，请确认是否继续操作？',
      autoFocusButton: null,
      class: 'modal-confirm-box',
      async onOk() {
        await switchRpa({
          rpaType: formValue.rpaType,
          tenant: modalInfo.tenantId
        })
        message.success('编辑成功')
        emit('operateSuccess')
        closeModal()
        resetModal()
      },
      onCancel() {}
    })
  }
}
</script>
<style lang="less" scoped>
.modify-box {
  padding: 16px 16px 0;
}
</style>
